package com.szmg.wishwalls.action;

import java.util.Collections;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.szmg.wishwalls.dto.DiscussDto;
import com.szmg.wishwalls.dto.ResultDto;
import com.szmg.wishwalls.dto.VoteDetailDto;
import com.szmg.wishwalls.dto.WeChatAccessToken;
import com.szmg.wishwalls.dto.WeChatUserInfo;
import com.szmg.wishwalls.dto.WishOrderDetailDto;
import com.szmg.wishwalls.model.Discuss;
import com.szmg.wishwalls.model.VoteDetail;
import com.szmg.wishwalls.model.WishOrder;
import com.szmg.wishwalls.service.WishOrderService;
import com.szmg.wishwalls.util.WeixinUtil;

@Controller("wishOrderAction")
public class WishOrderAction {
	private static final Logger log = LoggerFactory.getLogger(WishOrderAction.class);
	
	@Resource(name="wishOrderService")
	private WishOrderService wishOrderService;
	
    @Autowired  
    private  HttpServletRequest request;  
	
	@RequestMapping(value="/json/wishwall/wishOrder_saveWishOrder",method=RequestMethod.POST)
	@ResponseBody
	public ResultDto saveWishOrder(@RequestBody WishOrder wishOrder){
		ResultDto dto = new ResultDto();
		try{
			//当前许愿者没有许愿过，生成许愿单
			String[] productionIds = new String[0];
			if(null!= wishOrder && !StringUtils.isEmpty(wishOrder.getProductionIds())){
				productionIds = wishOrder.getProductionIds().split(",");
			}
			WeChatUserInfo userInfo = WeixinUtil.getUserinfo(queryBaseToken("session"), wishOrder.getWechatId());
			if(null == userInfo){//获取用户信息出错
				dto.setMsg("微信返回用户对象为null");
				dto.setState("0");
				return dto;
			}else if(!StringUtils.isEmpty(userInfo.getErrcode())){
				dto.setMsg("queryTokenNull errorCode="+userInfo.getErrcode()+",errorMsg="+userInfo.getErrmsg());
				dto.setState("0");
				return dto;
			}else{
				wishOrder.setNickName(userInfo.getNickName());
				wishOrder.setHeadImgUrl(userInfo.getHeadImgUrl());
				wishOrderService.saveWishOrder(wishOrder,wishOrder.getProgramCode(),productionIds);
				dto.setMsg("saveSuccess");
				dto.setState(wishOrder.getId());
				return dto;
			}
		}catch(Exception e){
			log.error("WishOrderAction saveWishOrder error!", e);
			dto.setMsg("saveError");
			dto.setState("0");
			return dto;
		}
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_saveVoteDetail",method=RequestMethod.POST)
    @ResponseBody
	public ResultDto saveVoteDetail(@RequestBody VoteDetailDto voteDetailDto){
		ResultDto dto = new ResultDto();
		try{
			//校验是否已经投过票
			if(wishOrderService.checkHadVoted(voteDetailDto)){//投过票
				dto.setMsg("hadVoted");
			}else{//未投过票
				wishOrderService.saveVoteDetail(voteDetailDto);
				dto.setMsg("saveSuccess");
			}
		}catch(Exception e){
			log.error("WishOrderAction saveWishOrder error!", e);
			dto.setMsg("saveError");
		}
		return dto;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_saveDiscuss",method=RequestMethod.POST)
    @ResponseBody
	public ResultDto saveDiscuss(@RequestBody Discuss discuss){
		ResultDto dto = new ResultDto();
		try{
			wishOrderService.saveDiscuss(discuss,null);
			dto.setMsg("saveSuccess");
		}catch(Exception e){
			log.error("WishOrderAction saveWishOrder error!", e);
			dto.setMsg("saveError");
		}
		return dto;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_queryWishOrderByWechatId",method=RequestMethod.GET)
    @ResponseBody
	public WishOrder queryWishOrderByWechatId(String wechatId,String programCode){
		WishOrder wishOrder = null;
		try{
			wishOrder = wishOrderService.queryWishOrderByWechatId(wechatId,programCode);
		}catch(Exception e){
			log.error("WishOrderAction queryWishOrderByWechatId error!", e);
		}
		return null == wishOrder ? new WishOrder() : wishOrder;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_queryDiscussByWishOrderId",method=RequestMethod.GET)
    @ResponseBody
	public List<DiscussDto> queryDiscussByWishOrderId(String wishOrderId){
		List<DiscussDto> discussDtoList = Collections.emptyList();
		try{
			discussDtoList = wishOrderService.queryDiscussByWishOrderId(wishOrderId);
		}catch(Exception e){
			log.error("WishOrderAction queryRootDiscussByWishOrderId error!", e);
		}
		return discussDtoList;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_queryVoteDetailsByRelationId",method=RequestMethod.GET)
    @ResponseBody
	public List<VoteDetail> queryVoteDetailsByRelationId(String wishOrderId,String productionId){
		List<VoteDetail> voteDetailList = Collections.emptyList();
		try{
			voteDetailList = wishOrderService.queryVoteDetailsByRelationId(wishOrderId, productionId);
		}catch(Exception e){
			log.error("WishOrderAction queryVoteDetailsByRelationId error!", e);
		}
		return voteDetailList;
	}

	@RequestMapping(value="/json/wishwall/wishOrder_queryWishOrderById",method=RequestMethod.GET)
    @ResponseBody
	public WishOrderDetailDto queryWishOrderById(String wishOrderId){
		WishOrderDetailDto wishOrderDto = null;
		try{
			wishOrderDto = wishOrderService.queryWishOrderDtoById(wishOrderId);
		}catch(Exception e){
			log.error("WishOrderAction queryWishOrderById error!", e);
		}
		return wishOrderDto;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_checkXuYuanButton",method=RequestMethod.GET)
    @ResponseBody
	public ResultDto checkXuYuanButton(String wechatId,String programCode){
		ResultDto dto = new ResultDto();
		try{
			boolean hadExists = wishOrderService.checkIsHadWishOrder(wechatId,programCode);
			if(hadExists){
				dto.setMsg("hadExists");
				return dto;
			}
			dto.setMsg("saveSuccess");
		}catch(Exception e){
			log.error("WishOrderAction checkXuYuanButton error!", e);
			dto.setMsg("saveError");
		}
		return dto;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_updateWishOrder",method=RequestMethod.POST)
	@ResponseBody
	public ResultDto updateWishOrder(String wishOrderId,String wishDeclaration){
		ResultDto dto = new ResultDto();
		try{
			wishOrderService.updateWishOrder(wishOrderId,wishDeclaration);
			dto.setMsg("saveSuccess");
			return dto;
		}catch(Exception e){
			log.error("WishOrderAction saveWishOrder error!", e);
			dto.setMsg("saveError");
			return dto;
		}
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_queryWechatInfo",method=RequestMethod.POST)
	@ResponseBody
	public WeChatUserInfo queryWechatInfo(String code){
		WeChatUserInfo dto = new WeChatUserInfo();
		try{
			WeChatAccessToken token = WeixinUtil.getAccessToken(WeixinUtil.APP_ID, WeixinUtil.APP_SECRET, code);
			if(null != token && !StringUtils.isEmpty(token.getToken()) 
					&& !StringUtils.isEmpty(token.getOpenid()) && StringUtils.isEmpty(token.getErrcode()) ){
				dto.setOpenId(token.getOpenid());
				dto.setState("1");
			}else{
				dto.setMsg("queryTokenNull code="+code+",errorCode="+token.getErrcode()+",errorMsg="+token.getErrmsg());
				dto.setState("0");
			}
		}catch(Exception e){
			log.error("WishOrderAction queryWechatInfo error!", e);
			dto.setMsg("queryError code="+code);
			dto.setState("0");
		}
		return dto;
		
//		try{
//			WeChatAccessToken token = WeixinUtil.getAccessToken(WeixinUtil.APP_ID, WeixinUtil.APP_SECRET, code);
//			if(null != token && !StringUtils.isEmpty(token.getToken()) 
//					&& !StringUtils.isEmpty(token.getOpenid()) && StringUtils.isEmpty(token.getErrcode()) ){
//				String baseToke = queryBaseToken("first");
//				dto = WeixinUtil.getUserinfo(baseToke, token.getOpenid());
//				if(null == dto){//重新获取token，再试一次
//					baseToke = queryBaseToken("new");
//					dto = WeixinUtil.getUserinfo(baseToke, token.getOpenid());
//					if(null == dto){
//						dto = new WeChatUserInfo();
//						dto.setMsg("queryUserNull code="+code+",Token="+token.getToken());
//						dto.setState("0");
//					}
//				}
//				dto.setOpenId(token.getOpenid());
//			}else{
//				dto.setMsg("queryTokenNull code="+code+",errorCode="+token.getErrcode()+",errorMsg="+token.getErrmsg());
//				dto.setState("0");
//			}
//		}catch(Exception e){
//			log.error("WishOrderAction queryWechatInfo error!", e);
//			dto.setMsg("queryError code="+code);
//			dto.setState("0");
//		}
//		return dto;
	}
	
	private String queryBaseToken(String type){
		String baseToke = "";
		if("first".equals(type)){//第一次获取，session没有token就调用接口获取，否则从session获取。
			if(null == request.getSession().getAttribute("baseToken")){
				System.out.println("------------------get new baseToken!");
				baseToke = WeixinUtil.getBaseAccessToken(WeixinUtil.APP_ID, WeixinUtil.APP_SECRET);
				request.getSession().setAttribute("baseToken",baseToke);
			}else{
				System.out.println("------------------user session baseToken!");
				baseToke = request.getSession().getAttribute("baseToken").toString();
			}
		}else if("new".equals(type)){//每次重新获取，不管session是否存在
			System.out.println("------------------type new get new baseToken!");
			baseToke = WeixinUtil.getBaseAccessToken(WeixinUtil.APP_ID, WeixinUtil.APP_SECRET);
			request.getSession().setAttribute("baseToken",baseToke);
		}else if("session".equals(type)){//每次从session获取
			System.out.println("------------------type session get baseToken!");
			if(null == request.getSession().getAttribute("baseToken")){
				return null;
			}else{
				baseToke = request.getSession().getAttribute("baseToken").toString();
			}
		}
		return baseToke;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_checkIsGuanzhu",method=RequestMethod.POST)
	@ResponseBody
	public WeChatUserInfo checkIsGuanzhu(String code,String openId){
		//调试代码，不通过网页授权获取openId，指定openId
		//request.getSession().setAttribute("userOpenId", "ovc_xjjFqUmqTf3iZaXNxKiWmmpo");
		//调试代码，不通过网页授权获取openId，指定openId
		WeChatUserInfo dto = new WeChatUserInfo();
		try{
			if(null == request.getSession().getAttribute("userOpenId")){
				WeChatAccessToken token = WeixinUtil.getAccessToken(WeixinUtil.APP_ID, WeixinUtil.APP_SECRET, code);
				if(null == token || StringUtils.isEmpty(token.getOpenid())){
					dto.setMsg("queryTokenNull code="+code+",errorCode="+token.getErrcode()+",errorMsg="+token.getErrmsg());
					dto.setState("0");
				}else{
					request.getSession().setAttribute("userOpenId", token.getOpenid());
					String baseToke = queryBaseToken("first");
					dto = WeixinUtil.getUserinfo(baseToke, token.getOpenid());
					if(null == dto || !StringUtils.isEmpty(dto.getErrcode())){//重新获取token，再试一次
						baseToke = queryBaseToken("new");
						dto = WeixinUtil.getUserinfo(baseToke, token.getOpenid());
						if(null == dto || !StringUtils.isEmpty(dto.getErrcode())){
							dto = new WeChatUserInfo();
							dto.setMsg("queryUserNull code="+code+",Token="+token.getToken());
							dto.setState("0");
						}
					}
				}
				dto.setOpenId(token.getOpenid());
			}else{
				String baseToke = queryBaseToken("first");
				dto = WeixinUtil.getUserinfo(baseToke, request.getSession().getAttribute("userOpenId").toString());
				if(null == dto || !StringUtils.isEmpty(dto.getErrcode())){//重新获取token，再试一次
					baseToke = queryBaseToken("new");
					dto = WeixinUtil.getUserinfo(baseToke, request.getSession().getAttribute("userOpenId").toString());
					if(null == dto || !StringUtils.isEmpty(dto.getErrcode())){
						dto = new WeChatUserInfo();
						dto.setMsg("queryUserNull code="+code+",session userOpenId="+request.getSession().getAttribute("userOpenId").toString());
						dto.setState("0");
					}
				}
			}
		}catch(Exception e){
			log.error("WishOrderAction queryWechatInfo error!", e);
			dto.setMsg("queryError code="+code);
			dto.setState("0");
		}
		return dto;
	}
	
	@RequestMapping(value="/json/wishwall/wishOrder_superAllProduction",method=RequestMethod.GET)
	@ResponseBody
	public ResultDto superAllProduction(String wishOrderId,String openId){
		ResultDto dto = new ResultDto();
		try{
			wishOrderService.superAllProduction(wishOrderId,openId);	
			dto.setState("1");
		}catch(Exception e){
			log.error("WishOrderAction queryWechatInfo error!", e);
			dto.setMsg("error!");
			dto.setState("0");
		}
		return dto;
	}
}
